import datetime
import json
import copy
import re
from collections import defaultdict, Counter
from itertools import chain
import logging
import dateutil.utils
import requests
from django.core.cache import cache
from django.db import connections as db_connections
from django.db.models import Q as orm_Q, Count
from django.http import HttpResponse

from ninja import Form, NinjaAPI
from requests.auth import HTTPBasicAuth
import hashlib


from api_v2.api_payload import SuperApi, CompanySearch, JobSearchApi, JobApi, QueryPush, KeywordQuery, LianxiPayload, \
    GetentidPayload, ContactPayload, MapSearchPayload, HeatMapPayload, XinHuaCompanySearch, TrademarkPayload, \
    TrademarkSearchPayload, PatentPayload, PatentSearch, BaiduBiddingPayload, BaiduBiddingSearch, \
    WeChatPayload, WeChatSearch, BatchQuery, BatchComplete, XinHuaMapSearchPayload, RelateContactPayload, RecentCourtOpen, \
    EntBasePayload, LegalAdvice, BankruptcyReorganization, FinancialService, CreditRepair, BankContactService
from submodule.models.dataplus.dataplus import BhLianxiCompanyCsv, BhDataplusPatent, BhDataplusPatentPlus, BhDataplusTminfo, BhDataplusTm, BhDataplusTmGg, BhDataplusTmGoods, \
    BhDataplusTmEnt, BhDataplusTmPics, BhDataplusJobInfo, BhTAggreDataindex
from submodule.utils.utils import salary_wash, get_entids_by_titles, format_datetime, namedtuplefetchall, ent_name_batch
from submodule.utils.utils import resulthandle, format_date, check_json_format
from submodule.models.saic.models import BhCompanyBasic, BhGetiBasic, BhCompanyManager, BhCompanyInv, BhCompanyNacao
from submodule.models.codes.dicts import ent_status, contact_source_dict, zhiwei_code
from submodule.models.codes.models import BhCodeRegion, BhCodeNic, BhCodeCa16

from submodule.utils.base62 import wldecode, wlencode
from submodule.utils.geo_location import handle_geohash, center_geolocation
from submodule.utils.pagination import pagination
from api_v2.utils import legal_service_q


from ninja import Redoc

api_v2 = NinjaAPI(version='2.0.0', docs=Redoc())

logger = logging.getLogger('ac_api')

@api_v2.get("/")
def index(request):
    return {'msg': 'dp-data-saas-api:v2'}


@api_v2.post("/getentid/", summary='获取entid', tags=['基础接口'], description='【已完成】')
def getentid(request, payload: GetentidPayload = Form(...)):
    result = {"code": "101", "data": ""}
    the_type = payload.ctype
    the_key = payload.key

    entid = None
    # 按信用代码/注册号精确查询
    if the_type == "1":
        model_field_map = [
            (BhCompanyBasic, orm_Q(UNISCID=the_key) | orm_Q(REGNO=the_key) | orm_Q(NACAOID=the_key)),
            (BhGetiBasic, orm_Q(UNISCID=the_key) | orm_Q(REGNO=the_key)),
            (BhCompanyNacao, orm_Q(UNISCID=the_key) | orm_Q(NACAOID=the_key))
        ]
        for model, q_query in model_field_map:
            obj = model.objects.filter(q_query).first()
            if obj:
                entid = obj.entid
                break
    # 按企业名称精确查询
    elif the_type == "2":
        entid_value = get_entids_by_titles([the_key])
        if entid_value:
            entid = entid_value[the_key]

    if entid:
        result['code'] = '200'
        result["data"] = wlencode(entid, addcrc=True)
    return result


@api_v2.post("/mohu/", summary='基础模糊', tags=['基础接口'], description='【未完成】依赖ES')
def mohu(request, key=Form(..., description="查询关键字")):
    context = {'code': '200', 'data': []}

    return HttpResponse(json.dumps(context, ensure_ascii=False), content_type="application/json")


@api_v2.post("/mohu_senior/", summary='高级模糊', tags=['基础接口'], description='【未完成】依赖ES')
def mohu_senior(request, key=Form(..., description="查询关键字")):
    context = {'code': '200', 'data': []}


    return HttpResponse(json.dumps(context, ensure_ascii=False), content_type="application/json")



@api_v2.post("/node_amount_statistics/", summary='企业节点数量统计', tags=['基础接口'], description='【已完成】')
def node_amount_statistics(request, entid=Form(..., description="企业唯一标识")):
    entid = wldecode(entid, True)
    context = {'code': '200', 'data': defaultdict(int)}
    if not entid:
        return context
    # 本地统计
    if entid < 500000000:
        local_ipr_index = [13, 14, 15, 16, 17, 41, 42, 43, 44]  # 知识产权 44为工商行政许可
    else:
        local_ipr_index = [13, 14, 15, 16, 17, 41, 42, 43, 45]  # 知识产权 45为个体户工商许可
    local_basic_index = [26, 27, 28, 29, 63]  # 工商信息
    local_listed_index = [54, 55, 56, 57, 58]  # 上市信息
    local_court_index = [11, 19, 20, 21, 46, 47, 48, 49, 50, 51, 52, 53]  # 企业风险
    local_operate_index = [1, 24]  # 经营信息
    local_job_index = [25]  # 招聘信息
    local_marketing_index = [30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 62]  # 营销推广
    local_bid_index = [22]  # 招标投标
    local_annual_index = [2, 3, 4, 5, 6, 7, 8, 9, 10]  # 企业年报

    local_index_list = local_basic_index + local_listed_index + local_court_index + local_operate_index + \
                       local_job_index + local_marketing_index + local_ipr_index + local_bid_index + local_annual_index
    local_dataindex_objs = BhTAggreDataindex.objects.filter(companyid=entid, model_index__in=local_index_list).values_list(
        "model_index", "dcount")
    local_index_num_dict = dict(local_dataindex_objs)
    local_tab_count_dict = {
        'ENTPOSTCOUNT': local_basic_index,
        'LISTCOMCOUNT': local_listed_index,
        'ENTRISKCOUNT': local_court_index,
        'MANAGINFOCOUNT': local_operate_index,
        'JOBCOUNT': local_job_index,
        'MARKPROCOUNT': local_marketing_index,
        'INTELPROPCOUNT': local_ipr_index,
        'TENDERBIDDCOUNT': local_bid_index,
        'ARCOUNT': local_annual_index,
    }
    for tab_name, tab_index in local_tab_count_dict.items():
        temp_data = sum(map(lambda x: local_index_num_dict.get(x, 0), tab_index))
        context['data'][tab_name] += temp_data
    # 工商信息+1（基本信息）
    context['data']['ENTPOSTCOUNT'] += 1
    # 上市信息+1（基本信息）
    if context['data']['LISTCOMCOUNT']:
        context['data']['LISTCOMCOUNT'] += 1
    return context


@api_v2.post("/job_search/", summary='招聘查询接口', tags=['企业详情'], description='【未完成】依赖ES')
def job_search(request, jobsearch: JobSearchApi = Form(...)):
    entid = jobsearch.entid
    entid = wldecode(entid, True)

    start, end = pagination(jobsearch.pageindex, jobsearch.pagesize)[:2]

    result = {'code': '200', 'total': 0, 'data': [], 'job_salary': [], 'job_area': [], 'job_experience': []}
    if entid < 1:
        return result

    return result


@api_v2.post("/company_search/", summary='企业探查', tags=['企业筛选'], description='【未完成】依赖ES')
def company_search(request, comopanysearch: CompanySearch = Form(...)):
    data = comopanysearch.dict() if comopanysearch else {}

    context = {"total": 0, "code": "200", "data": []}

    return context

@api_v2.post("/company_search/count/", summary='企业探查统计', tags=['企业筛选'], description='【未完成】依赖ES')
def company_search_count(request, comopanysearch: CompanySearch = Form(...)):
    data = comopanysearch.dict() if comopanysearch else {}


    context = {"total": 0, "code": "200", "data": []}
    return context


@api_v2.post("/xinhua_company_search/", summary='企业列表', tags=['新华'], description='【未完成】依赖ES')
def xinhua_company_search(request, payload: XinHuaCompanySearch = Form(...)):
    context = {"total": 0, "code": "200", "data": []}
    ent_name = payload.ent_name
    nic = payload.nic
    start, end, page_index, pagesize = pagination(payload.pageIndex, payload.pageSize)
    if start >= 200000:
        start = 200000 - pagesize
    end = pagesize + start

    return context


@api_v2.post("/super_api/", summary='高级查询', tags=['企业筛选'], description='【未完成】依赖ES')
def super_api(request, searchapi: SuperApi = Form(...)):
    context = {"total": 0, "code": "200", "data": []}
    query = searchapi.query
    start, end, page_index, pagesize = pagination(searchapi.pageindex, searchapi.pagesize)
    if start >= 200000:
        start = 200000 - pagesize
    end = pagesize + start

    return context


@api_v2.post("/super_api/count/", summary='高级查询计数', tags=['企业筛选计数'], description='【未完成】依赖ES')
def super_api_count(request, searchapi: SuperApi = Form(...)):
    query = searchapi.query
    start=0
    end=0
    # 过滤筛选条件

    context = {"total": 0, "code": "200", "data": []}
    return context

@api_v2.post("/company_batch_query/", summary='企业批量查询', tags=['企业筛选'], description='【未完成】依赖ES')
def company_batch_query(request, payload: BatchQuery = Form(...)):
    context = {"total": 0, "code": "200", "data": []}


    return context


@api_v2.post("/company_batch_complete/", summary='企业数据补全', tags=['企业筛选'], description='【未完成】依赖ES')
def company_batch_complete(request, payload: BatchComplete = Form(...)):
    context = {"total": 0, "code": "200", "data": []}

    return context


@api_v2.post("/company_query_push/", summary='企业查询推送', tags=['企业筛选'], description='【未完成】依赖ES')
def company_query_push(request, payload: QueryPush = Form(...)):
    pk = payload.id
    name = payload.name
    parameter = payload.parameter
    query_json = json.loads(parameter or '{}')

    result = {
        'id': pk,
        'name': name,
        'parameter': parameter,
        'dataPushDetailList': []
    }


    return {'code': '200'}


# 关键词匹配
@api_v2.post("/search_keyword/", summary='关键词匹配', tags=['企业筛选'], description='【未完成】依赖ES')
def search_keyword(request, payload: KeywordQuery = Form(...)):
    '''
    企业名、人名、产品、网站、地址、业务、号码、统一码
    '''
    entids = payload.entids
    keywordType = payload.keywordType
    keyword = payload.keyword

    search_result = defaultdict(list)
    entid_l = [wldecode(x, True) for x in entids.split(',')]

    return {'code': '200', 'data': search_result}


# 联系方式查询
@api_v2.post("/lianxi_receive/", summary='联系方式批量领取', tags=['联系方式'], description='【已完成】缺少联系人姓名职位')
def lianxi_receive(request, entids=Form(..., description='企业entid，使用逗号分隔')):
    entid_list = [wldecode(x, True) for x in entids.split(',') if x]

    result = {'code': '200','data':[]}
    obj_total = BhLianxiCompanyCsv.objects.filter(companyid__in=entid_list).count()
    result['total'] = obj_total
    obj = BhLianxiCompanyCsv.objects.filter(companyid__in=entid_list)[:500000]
    data = []


    # 座机 所在地
    tel_region = 'tel_region_dict'
    tel_region_dict = cache.get(tel_region)
    if not tel_region_dict:
        tel_region_obj = BhCodeRegion.objects.all().values_list('TEL', 'code')
        tel_region_dict = dict(tel_region_obj)
        cache.set(tel_region, tel_region_dict, 3600 * 24 * 7)
    region_cache_dict = BhCodeRegion.get_cache()

    for contact_info in obj.MOBILE.split(';'):
        data.append({
            'id': hashlib.md5((str(obj.companyid)+str(contact_info)+'mobile').encode('utf-8')).hexdigest(),  # 联系方式id
            'entid': wlencode(obj.companyid, True),  # 联系方式id
            'contact': contact_info,  # 联系方式
            'contact_type': '1',  # 联系方式类型
            'person': '',  # 联系人
            'person_post': '',  # 联系人职位
            'source': '',  # 来源
            'source_website': '',  # 来源网址
            'tag': '',  # 标签
            'area': '',  # 归属地
            'function_tag': '',  # 职能标签
        })

    for contact_info in obj.TEL.split(';'):
        mobile_area = ''
        mobile_region = ''
        tel_value = contact_info.split('-')
        if len(tel_value) == 2:
            mobile_region = tel_region_dict.get(tel_value[0])
        if mobile_region:
            region_obj = region_cache_dict.get(mobile_region)
            if region_obj:
                mobile_area = region_obj.get('fulltitle', '')
        data.append({
            'id': hashlib.md5((str(obj.companyid)+str(contact_info)+'tel').encode('utf-8')).hexdigest(),  # 联系方式id
            'entid': wlencode(obj.companyid, True),  # 联系方式id
            'contact': contact_info,  # 联系方式
            'contact_type': '2',  # 联系方式类型
            'person': '',  # 联系人
            'person_post': '',  # 联系人职位
            'source': '',  # 来源
            'source_website': '',  # 来源网址
            'tag': '',  # 标签
            'area': mobile_area,  # 归属地
            'function_tag': '',  # 职能标签
        })

    result['data'] = data

    return result


# 联系方式对象
@api_v2.post("/contact_obj/", summary='联系方式对象详情', tags=['联系方式'], description='【未完成】无联系人、来源等字段')
def contact_obj(request, payload: ContactPayload = Form(...)):
    entid = wldecode(payload.entid, True)
    contact_id = payload.contact_id
    result = {'code': '200'}

    return result


# 联系方式清洗
@api_v2.post("/contact_wash/", summary='联系方式清洗', tags=['联系方式'], description='【未完成】无单独联系方式字段')
def contact_wash(request, entids=Form(..., description="企业唯一标识"), lianxis=Form(..., description="联系方式")):
    entid_list = [wldecode(x, True) for x in entids.split(',')]
    lianxi_list = lianxis.split(',')
    result = {'code': '200'}

    return result


# 地图拓客
@api_v2.post("/map_search/", summary='地图拓客', tags=['企业筛选'], description='【未完成】依赖ES')
def map_search(request, payload: MapSearchPayload = Form(...)):
    context = {"code": "200", "total": 0, "center_point": {}, "data": []}


    return context


# 地图拓客
@api_v2.post("/xinhua_map_search/", summary='地图拓客', tags=['新华'], description='【未完成】依赖ES')
def xinhua_map_search(request, payload: XinHuaMapSearchPayload = Form(...)):
    context = {"code": "200", "total": 0, "claim_total": 0, "authentication_total": 0,  "center_point": {}, "data": []}


    return context


# 热力图
@api_v2.post("/heat_map/", summary='热力图', tags=['企业筛选'], description='【未完成】依赖ES')
def heat_map(request, payload: HeatMapPayload = Form(...)):
    context = {"code": "200", "data": []}
    if payload.distance == '0.0m' or payload.distance == '0.0km':
        return context

    return context

# 热力图坐标点企业高级查询
@api_v2.post("/heat_map_point_search/", summary='热力图坐标点企业高级查询', tags=['企业筛选'], description='【未完成】依赖ES')
def heat_map_point_search(request, payload: MapSearchPayload = Form(...)):
    """
    根据热力图坐标点查询附近的企业，支持更多筛选条件
    """
    context = {"code": "200", "total": 0, "center_point": {}, "data": []}


    return context

@api_v2.post("/patent/", summary='专利筛选接口', tags=['应用中心'], description='【未完成】依赖ES')
def patent(request, patent_payload: PatentPayload = Form(...)):
    context = {"code": "200", "total": 0, "center_point": {}, "data": []}

    return context


@api_v2.post("/patent_search/", summary='专利查询接口', tags=['应用中心'], description='【未完成】依赖ES')
def patent_search(request, patent_search_payload: PatentSearch = Form(...)):
    entid = patent_search_payload.entid
    entid = wldecode(entid, True)

    start, end = pagination(patent_search_payload.pageindex, patent_search_payload.pagesize)[:2]

    result = {'code': '200', 'total': 0, 'data': []}
    if not isinstance(entid, int) or entid < 1:
        return result

    return resulthandle(result)


@api_v2.post("/patent_detail/", summary="专利详情", tags=['应用中心'], description='【已完成】')
def patent_detail(request, pid=Form(..., description='专利pid')):
    result = {'code': '200', 'data': {}}
    if not pid:
        return result
    dataPlusPatent = BhDataplusPatent.objects.filter(mid=pid).first()
    if not dataPlusPatent:
        return result

    result['data'] = {
        'patent_apply_code': dataPlusPatent.sqh,
        'bulletin_code': dataPlusPatent.gkggh,
        'application_ent': dataPlusPatent.sqr,
        'patent_type': dataPlusPatent.get_ptype_display(),
        'patent_type_code': dataPlusPatent.zflh,
        'patent_type_name': dataPlusPatent.zflh,
        'agency': dataPlusPatent.zldljg,
        'agent': dataPlusPatent.dlr,
        'address': dataPlusPatent.dz,
        'division_application': dataPlusPatent.fasq,
        'int_application': dataPlusPatent.gjsq,
        'application_date': format_date(dataPlusPatent.sqrq),
        'bulletin_date': format_date(dataPlusPatent.gkggr),
        'warrant_bulletin_date': '',
        'category_type': dataPlusPatent.fcfl,
        'patent_sort_code': dataPlusPatent.flh,
        'designer': dataPlusPatent.fmr,
        'int_publishing': dataPlusPatent.gjgb,
        'finalists_date': format_date(dataPlusPatent.jrgjrq),
        'patent_sovereignty': '-',
        'patent_brief': '-',
    }
    dataPlusPatentContent = BhDataplusPatentPlus.objects.filter(mid=pid)
    if dataPlusPatentContent.exists():
        dataPlusPatentContent = dataPlusPatentContent.first()
        result['data']['patent_sovereignty'] = dataPlusPatentContent.zqx
        result['data']['patent_brief'] = dataPlusPatentContent.zy
    return resulthandle(result)


@api_v2.post("/baidu_bidding/", summary='百度竞价筛选接口', tags=['应用中心'], description='【未完成】缺少数据')
def baidu_bidding(request, bidding_payload: BaiduBiddingPayload = Form(...)):
    context = {"total": 0, 'baidu_bidding_total': 0, "code": "200", "data": []}

    return context


@api_v2.post("/baidu_bidding_search/", summary='百度竞价查询接口', tags=['应用中心'], description='【未完成】缺少数据')
def baidu_bidding_search(request, bidding_search: BaiduBiddingSearch = Form(...)):
    entid = bidding_search.entid
    entid = wldecode(entid, True)

    start, end = pagination(bidding_search.pageindex, bidding_search.pagesize)[:2]

    result = {'code': '200', 'total': 0, 'data': []}
    if not isinstance(entid, int) or entid < 1:
        return result

    return resulthandle(result)


@api_v2.post("/baidu_bidding_detail/", summary="百度竞价详情", tags=['应用中心'], description='【未完成】缺少数据')
def baidu_bidding_detail(request, mid=Form(..., description='百度竞价详情id')):
    result = {'code': '200', 'data': {}}
    if not mid:
        return result

    return resulthandle(result)


@api_v2.post("/wechat/", summary='微信公众号筛选接口', tags=['应用中心'], description='【未完成】缺少数据')
def wechat(request, wechat_payload: WeChatPayload = Form(...)):
    query_dict = {
        'must': [{'if_wechat_code': {'exist': '1'}}]
    }

    context = {"total": 0, 'wechat_total': 0, "code": "200", "data": []}

    return context


@api_v2.post("/wechat_search/", summary='微信公众号查询接口', tags=['应用中心'], description='【未完成】缺少数据')
def wechat_search(request, wechat_search_payload: WeChatSearch = Form(...)):
    result = {'code': '200', 'data': {}}

    entid = wechat_search_payload.entid

    return resulthandle(result)


@api_v2.post("/wechat_detail/", summary="微信公众号详情", tags=['应用中心'], description='【未完成】缺少数据')
def wechat_detail(request, pid: str = Form(..., description='详情id')):
    result = {'code': '200', 'data': {}}
    if not (pid and pid.isnumeric()):
        result['msg'] = '未查询到数据'
        return result

    return result


# ======================================================================================================================
@api_v2.post("/trademark/", summary='商标筛选接口', tags=['应用中心'], description='【未完成】依赖ES')
def trademark(request, trademarkPayload: TrademarkPayload = Form(...)):
    query_dict = {
        'must': [{'if_trademark': {'exist': '1'}}]
    }

    context = {"total": 0, 'trademark_total': 0, "code": "200", "data": []}

    return context


@api_v2.post("/trademark_search/", summary='商标查询接口', tags=['应用中心'], description='【未完成】依赖ES')
def trademark_search(request, trademarkSearchPayload: TrademarkSearchPayload = Form(...)):
    entid = trademarkSearchPayload.entid
    entid = wldecode(entid, True)

    start, end = pagination(trademarkSearchPayload.pageindex, trademarkSearchPayload.pagesize)[:2]

    result = {'code': '200', 'total': 0, 'data': []}
    if not isinstance(entid, int) or entid < 1:
        return result

    return result


@api_v2.post("/trademark_detail/", summary='商标详情接口', tags=['应用中心'], description='【已完成】')
def trademark_detail(request, pid: str = Form(..., description='商标详情id')):
    result = {'code': '200', 'trademark_detail': {}, 'trademark_post': [], 'trademark_project': []}
    if not (pid and pid.isnumeric()):
        return result
    obj = BhDataplusTm.objects.filter(mid=pid).first()
    obj_ent = BhDataplusTmEnt.objects.filter(mid=pid).first()
    obj_pic = BhDataplusTmPics.objects.filter(mid=pid).first()

    if obj:
        # 商标详情
        result['trademark_detail'] = {
            'trademark_pic': obj_pic.pic_path,
            'trademark_name': obj.tname,
            'application_ent': obj_ent.ENTNAME,
            'application_code': obj.tnum,
            'trademark_apply_date': obj.application_date,
            'trademark_sort': obj.get_tmcat_display(),
            'register_date': obj.reg_date,
            'trademark_type': obj.tstyle,
            'special_deadline': obj.tterm_to,
            'if_share_trademark': obj.iscommon,
            'agent': obj.agency,
            'status': obj.pstatus,
            'nationality': '',
            'post_code': '',
            'application_address': obj_ent.DOM,
            'application_eg_address': obj_ent.DOM_E,
        }
        # 商标公告信息
        post_list = BhDataplusTmGg.objects.filter(tnum=obj.tnum).order_by('-tdate')
        result['trademark_post'] = [
            {
                'post_name': item.title,
                'post_code': item.period,
                'post_date': format_date(item.tdate),
            } for item in post_list
        ]
        # 商标使用信息
        project_list = BhDataplusTmGoods.objects.filter(mid=pid)
        result['trademark_project'] = [
            {
                'commodity_service': item.goods_name,
                'group_name': item.similar_group,
            } for item in project_list
        ]


    return resulthandle(result)


@api_v2.post("/job/", summary='招聘筛选接口', tags=['应用中心'], description='【未完成】依赖ES')
def job(request, job_payload: JobApi = Form(...)):
    query_dict = {
        'must': [{'if_job_offer': {'exist': '1'}}]
    }
    context = {"total": 0, "code": "200", "data": []}

    return context


@api_v2.post("/ent_job/", summary='企业招聘接口', tags=['应用中心'], description='【未完成】依赖ES')
def ent_job(request, jobsearch: JobSearchApi = Form(...)):
    entid = jobsearch.entid
    entid = wldecode(entid, True)

    start, end = pagination(jobsearch.pageindex, jobsearch.pagesize)[:2]

    result = {'code': '200', 'total': 0, 'data': []}
    if not isinstance(entid, int) or entid < 1:
        return result

    return resulthandle(result, False)


@api_v2.post("/job_detail/", summary='招聘详情接口', tags=['应用中心'], description='【已完成】')
def job_detail(request, mid=Form(..., description="招聘信息id")):
    obj = BhDataplusJobInfo.objects.filter(mid=mid).first()
    if not obj:
        return {'code': 101}

    result = {'code': '200', 'data': []}
    result['data'] = {
        'entname': obj.ENTNAME,
        'post': obj.position,
        'salary': salary_wash(obj.salary),
        'title': obj.title,
        'city': obj.city,
        'district': obj.district,
        'pdate': obj.pdate.isoformat() if obj.pdate else '',
        'updated': format_datetime(obj.updated) if obj.updated else '',
        'education': obj.education,
        'experience': obj.experience,
        'ori_age': obj.ori_age,
        'weal': obj.weal,
        'source': obj.source,
        'industry': obj.industry,
        'url': obj.url or obj.m_url,
    }
    return result

@api_v2.post("/complex_search/", summary='综合搜索', tags=['企业筛选'], description='【未完成】依赖ES')
def complex_search(request,
                   key=Form(..., description="搜索关键词"),
                   page=Form('0', description="当前页码，默认0"),
                   size=Form('10', description="每页数量，默认10")):
    start, end = pagination(page, size)[:2]
    pagesize = int(size)

    return None


@api_v2.post("/contact_source/", summary='联系方式来源分类', tags=['联系方式'], description='【未完成】无联系人、来源等字段')
def contact_source(request, entid: str = Form(..., description='企业id'),
                            contact_version: str = Form('0', description="联系方式版本 0原始版 1关联穿透版 默认0")):
    result = {'code': '200', 'data': []}
    entid = wldecode(entid, True)
    if not entid:
        return result

    return result


@api_v2.post("/lianxi_search_new/", summary='联系方式查询_new', tags=['联系方式'], description='【未完成】无联系人、来源等字段')
def lianxi_search_new(request, payload: LianxiPayload = Form(...)):
    result = {'code': '200'}
    entid = payload.entid
    entid = wldecode(entid, True)
    if not entid:
        return result

    return resulthandle(result)


@api_v2.post("/contact_category/", summary='联系方式分类统计', tags=['联系方式'], description='【未完成】无联系人、来源等字段')
def contact_category(request, entid: str = Form(..., description="企业唯一标识"),
                         source_type: str = Form('', description="来源"),
                         contact_position: str = Form('', description="联系人职位"),
                         contact_version: str = Form('0', description="联系方式版本 0原始版 1关联穿透版 默认0")):

    result = {'code': '200', 'source': [], 'position': []}

    entid = wldecode(entid, True)
    if not entid:
        return result

    return result


@api_v2.post("/relate_contact_search/", summary='关联联系方式查询', tags=['联系方式'], description='【未完成】暂无数据')
def relate_contact_search(request, payload: RelateContactPayload = Form(...)):
    result = {'code': '200'}
    entid = payload.entid
    entid = wldecode(entid, True)
    if not entid:
        return result
    source_type = payload.source_type
    relate_type = payload.relate_type

    offset, end, pageindex, pagesize = pagination(payload.pageindex, payload.pagesize)

    return resulthandle(result)


@api_v2.post("/relate_contact_category/", summary='关联联系方式分类统计', tags=['联系方式'], description='【未完成】暂无数据')
def relate_contact_category(request, entid: str = Form(..., description="企业唯一标识"),
                         source_type: str = Form('', description="来源"),
                         relate_type: str = Form('', description="关联类型")):

    result = {'code': '200', 'source': [], 'relate': []}

    entid = wldecode(entid, True)
    if not entid:
        return result

    return result


@api_v2.post("/node_amount_with_child/", summary='企业节点数量统计带子节点', tags=['基础接口'], description='【已完成】')
def node_amount_detail(request, entid=Form(..., description="企业唯一标识")):
    entid = wldecode(entid, True)
    context = {'code': '200', 'data': defaultdict(int)}
    if not entid:
        return context
    node_dict = {
        'business_info': {  # 工商信息
            'stockholder_info': 26,  # 股东信息
            'executives_info': 27,  # 高管信息
            'out_investment': 63,  # 对外投资
            'register_change': 28,  # 注册变更
            'branch': 29,  # 分支机构
            'financing_process': 84,  # 融资历程
            'vc_merge': 91,  # 并购信息
        },
        'listed_info': {  # 上市信息
            'financial_briefing': 54,  # 财务简报
            'director_info': 55,  # 董监高成员任职情况
            'stockholder_fund': 56,  # 股东持股情况
            'member_profile': 57,  # 成员简介
            'placard_publicity': 58,  # 公告公示
        },
        'ent_risk': {  # 企业风险
            'abnormal_operation': 11,  # 经营异常
            'judgment_text': 46,  # 裁判文书
            'court_open_placard': 48,  # 开庭公告
            'court_announcement': 49,  # 法院公告
            'executed_person_info': 47,  # 被执行人
            'final_case': 50,  # 终本案件
            'exposure_station': 51,  # 曝光台
            'equity_pledge': 52,  # 股权质押
            'administrative_penalties': 53,  # 工商处罚
            'restrict_consumption': 21,  # 限制高消费
            'lesscredit_executed_person_info': 20,  # 失信被执行人
            'simple_logout_placard': 19,  # 简易注销公告
            'illegal_dishonest': 66,  # 严重违法失信
            'owing_tax': 69,  # 欠税信息
            'filing_info': 67,  # 立案信息
            'bankruptcy_info': 68,  # 破产重整
            'auction_info': 64,  # 司法拍卖
            'service_notice': 65,  # 送达公告
            'chattel_mortgage': 83,  # 动产抵押
            'judicial_assistance': 85,  # 司法协助
            'tax_abnormal': 90,  # 税务非正常户
            'tax_case': 88,  # 企业重大税收违法
            'tax_punish': 89,  # 税务行政处罚
            'ip_pledge': 97,  # 知识产权出质
            'creditor': 98,  # 债权人公告
            'stock_frost': 99,  # 版权冻结
            'complaint': 100,  # 消费投诉
            'land_mort': 101,  # 土地抵押
            'land_transfer': 102,  # 土地转让
        },
        'operate_info': {  # 经营信息
            'building_project': 1,  # 建筑工程
            'major_public': 24,  # 重大舆情
            'import_export_credit': 86,  # 进出口信用
            'double_random_check': 87,  # 双随机抽查
            'tax_state': 93,  # 税务资质
            'tax_rating': 94,  # 税务信用
            'case_check': 95,  # 抽查检查
            'fire_check': 96,  # 消防检查
        },
        'offers_info': {  # 招聘信息
            'offers_detail': 25,  # 招聘信息
        },
        'market_spread': {  # 营销推广
            'baidu_bidding': 30,  # 百度竞价
            'website_detect': 31,  # 官网监测
            'icp_record': 32,  # ICP备案
            'b2b_yellow_pages': 33,  # B2B黄页
            'encyclopedia_introduction': 34,  # 百科介绍
            'product_data': 62,  # 产品数据
            'e_commerce_data': 40,  # 电商数据
            'android_market': 35,  # 安卓市场
            'ios_market': 36,  # 苹果市场
            'weibo_info': 37,  # 微博信息
            'wechat_public_num': 38,  # 微信公众号
            'applet_data': 39,  # 微信小程序
        },
        'intellectual_property': {  # 知识产权
            'patent_info': 41,  # 专利信息
            'trademark_info': 42,  # 商标信息
            'software_copyright': 13,  # 软件著作权
            'certification_info': 17,  # 资质证书
            'work_copyright': 14,  # 作品著作权
            'management_system': 15,  # 管理体系认证
            'land_info': 43,  # 土地信息
            'forcibly_certificate': 16,  # 强制性产品认证
            'administrative_license': 44 if entid < 500000000 else 45,  # 行政许可
            'reg_person': 103,  # 注册人员
        },
        'bidding_info': {  # 招标投标
            'bidding_info': 22,  # 招标投标
        },
        'ent_annual_report': {  # 企业年报
            'website_info': 73,  # 网站信息
            'annual_report_assets': 74,  # 年报资产信息
            'equity_alter': 75,  # 股权变更
            'stockholder_fund': 76,  # 股东出资
            'foreign_invest': 77,  # 对外投资
            'foreign_vouch': 78,  # 对外担保
            'annual_report_social': 79,  # 年报社保信息
            'annual_report_alter': 80,  # 年度变更信息
        },
        'mohurd_info':{
            'reg_person': 103,  # 注册人员,
            'mohurd_project': 104,  # 企业业绩,
            'mohurd_cert': 105,  # 建筑证书,
            'recent_cert': 106,  # 即将过期资质,
            'upgrade_cert': 107,  # 可升级资质,
            'add_cert': 108,  # 可增项资质,
        },
    }

    local_index_list = [70, ]
    for item in node_dict.values():
        local_index_list.extend(item.values())
    local_dataindex_objs = BhTAggreDataindex.objects.filter(companyid=entid, model_index__in=local_index_list).values_list(
        "model_index", "dcount")
    local_index_num_dict = dict(local_dataindex_objs)
    for node_key, node_value in node_dict.items():
        for key, value in node_value.items():
            node_value[key] = local_index_num_dict.get(value, 0)
        if node_key == 'ent_annual_report':
            node_dict[node_key]['total'] = local_index_num_dict.get(70, 0)
        else:
            node_dict[node_key]['total'] = sum(node_value.values())
    context['data'] = node_dict
    return context

@api_v2.post("/recent_court_open/", summary='法律服务-近期开庭', tags=['应用中心'], description='【未完成】暂无ES数据')
def recent_court_open(request, payload: RecentCourtOpen = Form(...)):
    result = {'code': '200', 'data': [], 'total': 0}

    return result

@api_v2.post("/recent_court_open/select_count/", summary='法律服务-近期开庭-高筛统计', tags=['应用中心'], description='【未完成】暂无ES数据')
def recent_court_open_select_count(request, payload: RecentCourtOpen = Form(...)):
    result = {'code': '200', 'data': [], 'total': 0}

    context = {"total": 0, "code": "200", "data": []}
    return context

@api_v2.post("/recent_court_open/count/", summary='法律服务-近期开庭-统计', tags=['应用中心'], description='【未完成】暂无ES数据')
def recent_court_open_count(request, payload: RecentCourtOpen = Form(...)):
    result = {'code': '200', 'data': [], 'total': 0}

    context = {"total": 0, "code": "200", "data": []}
    return context

@api_v2.post("/legal_advice/", summary='法律服务-法律咨询', tags=['应用中心'], description='【未完成】暂无ES数据')
def legal_advice(request, payload: LegalAdvice = Form(...)):
    result = {'code': '200', 'data': [], 'total':0}

    return result

@api_v2.post("/legal_advice/select_count/", summary='法律服务-法律咨询-高筛统计', tags=['应用中心'], description='【未完成】暂无ES数据')
def legal_advice_select_count(request, payload: LegalAdvice = Form(...)):

    context = {"total": 0, "code": "200", "data": []}
    return context

@api_v2.post("/legal_advice/count/", summary='法律服务-法律咨询-统计', tags=['应用中心'], description='【未完成】暂无ES数据')
def legal_advice_count(request, payload: LegalAdvice = Form(...)):

    context = {"total": 0, "code": "200", "data": []}
    return context

@api_v2.post("/bankruptcy_reorg/", summary='法律服务-破产重整', tags=['应用中心'], description='【未完成】暂无ES数据')
def bankruptcy_reorganization(request, payload: BankruptcyReorganization=Form(...)):
    result = {'code': '200', 'data': [], 'total':0}

    return result

@api_v2.post("/bankruptcy_reorg/select_count/", summary='法律服务-破产重整-高筛统计', tags=['应用中心'], description='【未完成】暂无ES数据')
def bankruptcy_reorganization_select_count(request, payload: BankruptcyReorganization=Form(...)):

    context = {"total": 0, "code": "200", "data": []}
    return context

@api_v2.post("/bankruptcy_reorg/count/", summary='法律服务-破产重整-统计', tags=['应用中心'], description='【未完成】暂无ES数据')
def bankruptcy_reorganization_count(request, payload: BankruptcyReorganization=Form(...)):
    # 通用查询处理
    payload_dict = payload.dict()
    filter_list = legal_service_q(payload_dict)
    must_not = []

    context = {"total": 0, "code": "200", "data": []}
    return context

@api_v2.post("/credit_repair/", summary='法律服务-信用修复', tags=['应用中心'], description='【未完成】暂无ES数据')
def credit_repair(request, payload: CreditRepair=Form(...)):
    result = {'code': '200', 'data': [], 'total':0}
    pageIndex = payload.pageIndex
    pageSize = payload.pageSize
    start, end = pagination(pageIndex, pageSize)[:2]

    return result

@api_v2.post("/credit_repair/select_count/", summary='法律服务-信用修复-高筛统计', tags=['应用中心'], description='【未完成】暂无ES数据')
def credit_repair_select_count(request, payload: CreditRepair=Form(...)):
    # 通用查询处理
    payload_dict = payload.dict()

    context = {"total": 0, "code": "200", "data": []}
    return context

@api_v2.post("/credit_repair/count/", summary='法律服务-信用修复-统计', tags=['应用中心'], description='【未完成】暂无ES数据')
def credit_repair_count(request, payload: CreditRepair=Form(...)):
    # 通用查询处理
    payload_dict = payload.dict()
    filter_list = legal_service_q(payload_dict)
    must_not = []

    context = {"total": 0, "code": "200", "data": []}

    return context

@api_v2.post("/legal/industry/", summary='法律服务-制造、建筑、金融企业', tags=['应用中心'], description='【未完成】暂无ES数据')
def legal_idustry(request, payload: EntBasePayload=Form(...)):
    result = {'code': '200', 'data': [], 'total': 0}

    return result

@api_v2.post("/legal/industry/select_count/", summary='法律服务-制造、建筑、金融企业-高筛统计', tags=['应用中心'], description='【未完成】暂无ES数据')
def legal_idustry_select_count(request, payload: EntBasePayload=Form(...)):
    payload_dict = payload.dict()
    # 通用查询处理
    filter_list = legal_service_q(payload_dict)
    must_not=[]
    should_list=[]

    context = {"total": 0, "code": "200", "data": []}

    return context

@api_v2.post("/legal/industry/count/", summary='法律服务-制造、建筑、金融企业-统计', tags=['应用中心'], description='【未完成】暂无ES数据')
def legal_idustry_count(request, payload: EntBasePayload=Form(...)):
    payload_dict = payload.dict()
    # 通用查询处理

    context = {"total": 0, "code": "200", "data": []}

    return context

@api_v2.post("/legal/industry_financial/", summary='法律服务-金融企业', tags=['应用中心'], description='【未完成】暂无ES数据')
def legal_idustry_financial(request, payload: EntBasePayload=Form(...)):
    result = {'code': '200', 'data': [], 'total': 0}

    return result


@api_v2.post("/legal/industry_financial/count/", summary='法律服务-金融企业-统计', tags=['应用中心'], description='【未完成】暂无ES数据')
def legal_idustry_financial_count(request, payload: EntBasePayload=Form(...)):
    payload_dict = payload.dict()
    # 通用查询处理
    filter_list = legal_service_q(payload_dict)
    must_not=[]
    should_list=[]

    context = {"total": 0, "code": "200", "data": []}

    return context


@api_v2.post("/legal/industry_financial/select_count/", summary='法律服务-金融企业-高筛统计', tags=['应用中心'], description='【未完成】暂无ES数据')
def legal_idustry_financial_select_count(request, payload: EntBasePayload=Form(...)):
    payload_dict = payload.dict()
    # 通用查询处理
    filter_list = legal_service_q(payload_dict)
    must_not=[]
    should_list=[]
    context = {"total": 0, "code": "200", "data": []}

    return context



@api_v2.post("/financial_all_nic_ent/", summary='金融服务--各类企业', tags=['应用中心'], description='【未完成】暂无ES数据')
def legal_service(request, payload: FinancialService = Form(...)):
    context = {'code': '200', 'data': []}

    return context

@api_v2.post("/financial_bid/", summary='金融服务--中标贷企业', tags=['应用中心'], description='【未完成】暂无ES数据')
def legal_service(request, payload: FinancialService = Form(...)):

    context = {"total": 0, "code": "200", "data": []}

    return context

@api_v2.post("/legal_action/count/", summary='法律服务-法律诉讼企业-统计', tags=['法律服务'], description='【未完成】暂无ES数据')
def legal_action_count(request, searchapi: SuperApi = Form(...)):

    context = {"total": 0, "code": "200", "data": []}

    return context

@api_v2.post("/be_executed/count/", summary='法律服务-被执行企业-统计', tags=['法律服务'], description='【未完成】暂无ES数据')
def be_executed_count(request, searchapi: SuperApi = Form(...)):

    context = {"total": 0, "code": "200", "data": []}

    return context

@api_v2.post("/be_limit_high/count/", summary='法律服务-限高企业-统计', tags=['法律服务'], description='【未完成】暂无ES数据')
def be_limit_high_count(request, searchapi: SuperApi = Form(...)):

    context = {"total": 0, "code": "200", "data": []}

    return context

@api_v2.post("/be_punish/count/", summary='法律服务-行政处罚企业-统计', tags=['法律服务'], description='【未完成】暂无ES数据')
def be_punish_count(request, searchapi: SuperApi = Form(...)):

    context = {"total": 0, "code": "200", "data": []}
    return context

@api_v2.post("/be_tax_punish/count/", summary='法律服务-税务处罚企业-统计', tags=['法律服务'], description='【未完成】暂无ES数据')
def be_tax_punish_count(request, searchapi: SuperApi = Form(...)):
    context = {"total": 0, "code": "200", "data": []}
    return context

@api_v2.post("/legal_action_area/count/", summary='法律行业数据分析-诉讼办理热度分布', tags=['法律服务'], description='【未完成】暂无ES数据')
def legal_action_area_count(request, searchapi: SuperApi = Form(...)):
    filter_list = []
    context = {"total": 0, "code": "200", "data": []}
    return context


@api_v2.post("/bank_contact_number/", summary='宁波银行-联系方式', tags=['联系方式'], description='【未完成】暂无数据')
def bank_contact_number(request, payload: BankContactService = Form(...)):
    credit_code = payload.credit_code
    result = {"code": "200", "data": ""}

    return result



